package sketch.specs;

import java.io.File;
import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.eclipse.jdt.core.dom.Comment;
import org.eclipse.jdt.core.dom.CompilationUnit;

import randoop.util.Files;
import sketch.util.Checker;

class FileContents {
	
	public static Map<String, List<String>> fileContents = new LinkedHashMap<String, List<String>>();
	
	public static void addFile(String filePath) {
		if(fileContents.containsKey(filePath)) {
			return;
		}
		//read a file
		try {
			List<String> fileContent = Files.readWhole(new File(filePath));
			fileContents.put(filePath, fileContent);
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
	}
	
	public static String fetchCommentString(String filePath, Comment comment, CompilationUnit unit) {
		return fetchString(filePath,
				unit.getLineNumber(comment.getStartPosition()), unit.getColumnNumber(comment.getStartPosition()),
				unit.getLineNumber(comment.getStartPosition() + comment.getLength()),
				unit.getColumnNumber(comment.getStartPosition() + comment.getLength()));
	}
	
	public static String fetchString(String filePath, int startRow, int startColumn, int endRow, int endColumn) {
		Checker.checkTrue(fileContents.containsKey(filePath), "The file: " + filePath + " does not " +
				"exist in the cached map, please call addFiles(String) first!");
		
		Checker.checkTrue(endRow >= startRow, "End row: " + endRow + " should >= " + startRow);
		if(endRow == startRow) {
			Checker.checkTrue(endColumn >  startColumn, "End column: " + endColumn + " should > start column: " + startColumn);
		}
		
		StringBuilder sb = new StringBuilder();
		int startRowInList = startRow - 1;
		//int endRowInList = endRow - 1;
		
		String str = fileContents.get(filePath).get(startRowInList);
		if(endRow == startRow) {
		    str = str.substring(startColumn, endColumn);
		    sb.append(str);
		} else {
			//throw new RuntimeException("Do not write in multiple lines, startRow: " + startRow + ", endRow: " + endRow);
			//simply ignore that
		}
		
		return sb.toString();
	}
	
}